package cn.com.vs;

import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.com.vs.service.ActivityService;
import cn.com.vs.service.CloudMapService;
import cn.com.vs.service.IMService;
import cn.com.vs.service.RedisService;
import cn.com.vs.utils.DBUtils;

import com.mashape.unirest.http.Unirest;
import com.mchange.v2.c3p0.ComboPooledDataSource;


public class StartupListener implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		setupSSL();
		String path = sce.getServletContext().getRealPath("/WEB-INF");
		PropertyConfigurator.configureAndWatch(path + File.separator + "conf" + File.separator + "log4j.properties");
		Configurator.init(path + File.separator + "conf" + File.separator + "conf.json");
	    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext( sce.getServletContext() );
	    ComboPooledDataSource datasource = (ComboPooledDataSource)ctx.getBean("ds");
		DBManager.getInstance().init(datasource);
		SqlSessionFactory fact = (SqlSessionFactory)ctx.getBean("sqlSessionFactory");
		try {
			DBUtils.init( fact );
		} catch (Exception e) {
			e.printStackTrace();
		}
		IMService.init();
		
		RedisService.init();
		
		CloudMapService.init();
		
		// 激活活动过期检测线程
		ActivityService.getInstance().init();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		try {
			Unirest.shutdown();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void setupSSL(){
		SSLContextBuilder builder = SSLContexts.custom();
		try {
			builder.loadTrustMaterial(null, new TrustStrategy() {
			    @Override
			    public boolean isTrusted(X509Certificate[] chain, String authType)
			            throws CertificateException {
			        return true;
			    }
			});
			SSLContext sslContext = builder.build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
			        sslContext, new X509HostnameVerifier() {
			            @Override
			            public void verify(String host, SSLSocket ssl)
			                    throws IOException {
			            }

			            @Override
			            public void verify(String host, X509Certificate cert)
			                    throws SSLException {
			            }

			            @Override
			            public void verify(String host, String[] cns,
			                    String[] subjectAlts) throws SSLException {
			            }

			            @Override
			            public boolean verify(String s, SSLSession sslSession) {
			                return true;
			            }
			        });

			Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
			        .<ConnectionSocketFactory> create().register("https", sslsf)
			        .register("http", new PlainConnectionSocketFactory()).build();

			PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
			        socketFactoryRegistry);
			CloseableHttpClient httpclient = HttpClients.custom()
			        .setConnectionManager(cm).build();
		    Unirest.setHttpClient(httpclient);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		
	}

}
